import {
  CompressOutlined,
  ExpandOutlined,
  LoadingOutlined,
  MehOutlined,
  PauseCircleOutlined,
  PlayCircleOutlined,
  SoundOutlined,
} from '@ant-design/icons';
import React, { useEffect, useRef, useState } from 'react';
import './index.less';

interface VideoPlayerProps {
  isExpanded?: boolean;
  src?: string;
  poster?: string;
  title?: string;
  autoPlay?: boolean;
  showTitle?: boolean;
  loop?: boolean;
  controls?: boolean;
  className?: string;
  onIsExpandedChange: () => void;
}

const VideoPlayer: React.FC<VideoPlayerProps> = ({
  isExpanded,
  src = '',
  poster = '',
  title = '',
  autoPlay = true,
  showTitle = true,
  loop = false,
  controls = true,
  className = '',
  onIsExpandedChange,
}) => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const progressRef = useRef<HTMLDivElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const [isPlaying, setIsPlaying] = useState(autoPlay);
  const [isMuted, setIsMuted] = useState(false);
  const [volume, setVolume] = useState(1);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [showControls, setShowControls] = useState(true);

  const togglePlay = () => {
    const video = videoRef.current;
    if (!video) return;

    if (isPlaying) {
      video.pause();
    } else {
      video.play().catch(() => setIsPlaying(false));
    }
    setIsPlaying(!isPlaying);
    setShowControls(true);
  };

  const toggleMute = () => {
    const video = videoRef.current;
    if (!video) return;

    video.muted = !isMuted;
    setIsMuted(!isMuted);
    setShowControls(true);
  };

  const handleVolumeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const video = videoRef.current;
    if (!video) return;

    const newVolume = parseFloat(e.target.value);
    video.volume = newVolume;
    setVolume(newVolume);
    setIsMuted(newVolume === 0);
    setShowControls(true);
  };

  const handleProgressClick = (e: React.MouseEvent<HTMLDivElement>) => {
    const video = videoRef.current;
    if (!video || !progressRef.current || duration === 0) return;

    const progressBar = e.currentTarget;
    const clickPosition = e.clientX - progressBar.getBoundingClientRect().left;
    const progressBarWidth = progressBar.clientWidth;
    const seekTime = (clickPosition / progressBarWidth) * duration;

    video.currentTime = seekTime;
    setCurrentTime(seekTime);
    setShowControls(true);
  };

  const toggleFullscreen = () => {
    if (!containerRef.current) return;

    if (!isFullscreen) {
      containerRef.current.requestFullscreen?.().catch((err) => {
        console.error('全屏错误:', err);
      });
    } else {
      document.exitFullscreen?.();
    }
    setShowControls(true);
  };

  const formatTime = (time: number) => {
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  };

  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    const handleLoadedData = () => {
      setIsLoading(false);
      setDuration(video.duration);
      if (autoPlay) video.play().catch(() => setIsPlaying(false));
    };

    const handleTimeUpdate = () => {
      setCurrentTime(video.currentTime);
      if (progressRef.current) {
        const progress = (video.currentTime / duration) * 100;
        progressRef.current.style.width = `${progress}%`;
      }
    };

    const handleEnded = () => {
      setIsPlaying(false);
    };

    video.addEventListener('loadeddata', handleLoadedData);
    video.addEventListener('timeupdate', handleTimeUpdate);
    video.addEventListener('ended', handleEnded);

    return () => {
      video.removeEventListener('loadeddata', handleLoadedData);
      video.removeEventListener('timeupdate', handleTimeUpdate);
      video.removeEventListener('ended', handleEnded);
    };
  }, [autoPlay, duration]);

  // 控制视频播放状态和显示控制条
  useEffect(() => {
    if (!controls) return;

    let timeout: NodeJS.Timeout; // 使用局部变量替代状态

    const hideControls = () => {
      if (isPlaying) {
        timeout = setTimeout(() => setShowControls(false), 3000);
      }
    };

    if (showControls) {
      hideControls();
    }

    return () => {
      clearTimeout(timeout); // 清理局部变量
    };
  }, [isPlaying, showControls, controls]); // 移除 controlsTimeout 依赖
  useEffect(() => {
    const handleFullscreenChange = () => {
      setIsFullscreen(!!document.fullscreenElement);
    };

    document.addEventListener('fullscreenchange', handleFullscreenChange);
    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
    };
  }, []);

  // 滚轮调节音量
  const handleWheelVolume = (e: React.WheelEvent<HTMLDivElement>) => {
    e.preventDefault();
    const video = videoRef.current;
    if (!video) return;

    // 滚轮向上增加音量，向下减小音量
    const delta = e.deltaY > 0 ? -0.05 : 0.05;
    const newVolume = Math.min(1, Math.max(0, volume + delta));

    video.volume = newVolume;
    setVolume(newVolume);
    setIsMuted(newVolume === 0);
    setShowControls(true);
  };

  return (
    <div
      ref={containerRef}
      className={`video-player ${className} ${isFullscreen ? 'fullscreen' : ''}`}
      style={{ flex: isExpanded ? '1 0 100%' : '1 0 60%' }}
      onMouseMove={() => controls && setShowControls(true)}
      onMouseLeave={() => controls && isPlaying && setShowControls(false)}
      onWheel={handleWheelVolume}
    >
      <div className="video-container">
        <video
          onClick={(e) => {
            e.stopPropagation();
            togglePlay();
          }}
          ref={videoRef}
          src={src}
          poster={poster}
          loop={loop}
          muted={isMuted}
        />

        {!src ? (
          <div className="empty-state">
            <PlayCircleOutlined className="empty-icon" />
            <div className="empty-text">现在没有视频正在播放哦</div>
          </div>
        ) : (
          isLoading && (
            <div className="loading-overlay">
              <LoadingOutlined className="spinner" />
            </div>
          )
        )}

        {showTitle && title && <div className="video-title">{title}</div>}

        {controls && (
          <div className={`controls ${showControls ? 'visible' : ''}`}>
            <div className="progress-bar" onClick={handleProgressClick}>
              <div
                ref={progressRef}
                className="progress"
                style={{ width: `${(currentTime / duration) * 100}%` }}
              />
            </div>

            <div className="controls-bottom">
              <div className="left-controls">
                <button
                  type="submit"
                  className="control-btn"
                  onClick={togglePlay}
                >
                  {isPlaying ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
                </button>

                <div className="volume-control">
                  <button
                    type="submit"
                    className="control-btn"
                    onClick={toggleMute}
                  >
                    {isMuted || volume === 0 ? (
                      <MehOutlined />
                    ) : (
                      <SoundOutlined />
                    )}
                  </button>
                  <input
                    type="range"
                    min="0"
                    max="1"
                    step="0.01"
                    value={isMuted ? 0 : volume}
                    onChange={handleVolumeChange}
                    className="volume-slider"
                  />
                </div>

                <div className="time-display">
                  {formatTime(currentTime)} / {formatTime(duration || 0)}
                </div>
              </div>

              <div className="right-controls">
                <button
                  type="submit"
                  className="control-btn"
                  onClick={toggleFullscreen}
                >
                  {isFullscreen ? <CompressOutlined /> : <ExpandOutlined />}
                </button>
                <button
                  type="submit"
                  className="control-btn"
                  onClick={onIsExpandedChange}
                >
                  {isExpanded ? '展开  ◄' : '折叠   ►'}
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default VideoPlayer;
